<template>
  <div style="height: 100%;">
    <el-container>
      <el-header>
        <div>
          <img src="../assets/heima.png" alt="" />
          <!-- <img src="/heima.png" alt="" /> -->
          <span>电商后台管理系统</span>
        </div>
        <el-button @click="logout()">退出</el-button>
      </el-header>
      <el-container>
        <el-aside width="200px">
          <el-menu :default-active="activePath" background-color="#333744" text-color="#fff" active-text-color="#ffd04b" :router="true">
            <el-submenu v-for="menu in menus" :key="menu.id" :index="menu.id + ''">
              <template slot="title">
                <i class="el-icon-location"></i>
                <span>{{ menu.authName }}</span>
              </template>
              <el-menu-item v-for="submenu in menu.children" :key="submenu.id" :index="'/' + submenu.path">
                <span>{{ submenu.authName }}</span>
              </el-menu-item>
            </el-submenu>
          </el-menu>
        </el-aside>
        <el-main>
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
export default {
  data() {
    return {
      menus: [],
      activePath: ''
    }
  },
  methods: {
    logout() {
      window.sessionStorage.removeItem('login_token')
      this.$router.push('/login')
    }
  },
  watch: {
    activePath() {
      window.sessionStorage.setItem('activePath', this.activePath)
    }
  },
  async created() {
    this.activePath = window.sessionStorage.getItem('activePath')
    const { data: res } = await this.$http.get('menus')
    console.log(res)
    if (res.meta.status !== 200) {
      return this.$message.error('左侧菜单加载失败')
    }
    this.menus = res.data
  },
  beforeRouteEnter(to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不！能！获取组件实例 `this`
    // 因为当守卫执行前，组件实例还没被创建
    console.log('beforeRouteEnter')
    next(vm => {
      vm.activePath = to.path
    })
  },
  beforeRouteUpdate(to, from, next) {
    // 在当前路由改变，但是该组件被复用时调用
    // 举例来说，对于一个带有动态参数的路径 /foo/:id，在 /foo/1 和 /foo/2 之间跳转的时候，
    // 由于会渲染同样的 Foo 组件，因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
    console.log('beforeRouteUpdate')
    this.activePath = to.path
    next()
  },
  beforeRouteLeave(to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    console.log('beforeRouteLeave')
    next()
  }
}
</script>

<style lang="less" scoped>
.el-container {
  height: 100%;
}

.el-header {
  background-color: #373d41;
  color: #fff;
  text-align: center;
  line-height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  > div {
    height: 60px;
    display: flex;
    align-items: center;
    span {
      margin-left: 15px;
    }
  }
}

.el-aside {
  background-color: #333744;
  color: #333;
  // text-align: center;
  // line-height: 200px;
}

.el-main {
  background-color: #e9eef3;
  color: #333;
  // text-align: center;
  // line-height: 160px;
}
</style>
